<template>
  <div class="control-setter">
    <div v-if="loadingCount > 0" class="mask">
      <a-spin class="spinner" />
    </div>
    <!-- <Hform
      v-if="formItems && formItems.length > 0"
      :items="formItems"
      :form-data="formData"
      @toggleGroup="toggleGroup"
      @change="onChange"
    ></Hform> -->

    <form-render
      v-if="Object.keys(formData).length > 0"
      from="panel"
      :chart-type="chartType"
      :widget-type="currentGridItem.widgetType"
      :form-data="formData"
      :widget-info="dataQuery"
      :interact-info="interactList"
      :panel-list="formItems"
      :dataset-list="projectDataset"
      :project-id="projectId"
      class="form-render"
      @change="onFormSettingChange"
      @reset="onFormSettingReset"
    />
  </div>
</template>

<script lang="ts">
/* eslint-disable no-unreachable */
import { dataBindKeys } from '@/config/setting-data-bind'
// import { tcolumnQueryDetail } from '@/api/visualization'
import { infoData, queryDatalist2 } from '@/api/data-list'
import {
  GeoMapGlyphChangedCallback,
  getGraphDataColumns,
  // gridItemIsDataClean,
  gridItemIsMyComponent,
  gridItemIsRecommend,
  numberTypes,
} from '@/util/common'
import {
  // ChartDataTypeEnum,
  // ChartDetailsEnum,
  filterTypeName,
  GeoMapEnableGlyphTypes,
  GEOMAP_NAME,
  GRAPH_ARRAY,
} from '@/config/contant'
import {
  cloneDeep,
  isString,
  isArray,
  isNumber,
  isEqual,
  throttle,
} from 'lodash'
import Hform from '@/components/form/h-form.vue'
import FormRender from '@/components/common/VisualizationDashboard/FormRender.vue'
import ChartProtoConfig from '@/components/common/VisualizationComp/proto-config'
import {
  parseSettingToChartOption,
  parseChartType,
  // parseChartOptionToFormSettiong,
  // parseChartProtoConfig,
} from '@/components/common/VisualizationDashboard/util'

import {
  getRelateWidgets,
  getWidgetData,
  loadGraphData,
  queryWidgetColumn,
} from '@/api/widget'
import { queryDatasetById } from '@/api/data'
// import { pipelineList } from '@/api/pipeline'
import { Component, Vue, Watch } from 'vue-property-decorator'
import PanelSetter from '@/components/controlSetter/PanelSetter.vue'
import VisualizationStore from '@/store/modules/visualization'
import {
  // getSettingConfig,
  getWidgetJson,
  getDefaultFormData,
} from '@/config/setting-chart'
import {
  KeyValueStore,
  GridItemDataInterface,
  ControlConfigurationInterface,
  componentTypeEnum,
  gridItemFilterInterface,
} from '../vueGridLayout/interfate/grid-Item-data-inteface'
import KV from '../form/kv'
import { message } from 'ant-design-vue'
import { loadListFiles } from '@/api/graph-analysis'
import visGraphService from '@/store/modules/vis-graph-service'

const filterColumnDefault = [{ value: '', type: 'string', step: 1 }]
// import { allNodeList } from '@/api/task'

// 监听到本数组即重新刷新数据并绑定
const dataWatchKeys = new Set([
  // 通用
  'dataId',
  'labelKey',
  'valueKey',
  'labelKeyFormat',
  'groupBy',
  'labelKeyY',
  'topK',
  'showNumber',
  'isAggr',
  'labelSortY',
  'labelSort',
  // geoMap
  'glyph',
  'mapTheme',
  'encodingType',
  'pointType',
  'pointColor',
  'pointRadius',
  'polygonColor',
  'borderColor',
  'borderWidth',
  'heatmapRadius',
  // heatmapMatrix
  'labelKeyY',
])

@Component({
  components: {
    Hform,
    PanelSetter,
    FormRender,
  },
})
export default class ControlSetter extends Vue {
  // 控制加载状态
  loadingCount: number = 0

  /**
   * 列信息
   */
  public columnsOptions: Array<any> = []

  /**
   * 配置项
   */
  public formItems: Array<KeyValueStore> = []

  /**
   * 绑定数据
   */
  formData: KeyValueStore = {}

  public get currentGridItem() {
    return VisualizationStore.currentGridItem
  }

  private get chartType() {
    return parseChartType(this.currentGridItem?.chartType || '')
  }

  /**
   * 项目里数据导入+pipeline的列表
   */
  private get projectDataset() {
    return VisualizationStore.datasetPipelineDataList
  }

  private get dataQuery() {
    // getData 接口查询参数，即{id, type, widgetJson}
    if (this.currentGridItem?.dataQuery) {
      // const {dataId, dataType} = this.currentGridItem.chartOptions
      // return {
      //   id: dataId,
      //   type: dataType,
      //   widgetJson: this.currentGridItem?.dataQuery.data
      // }

      return this.currentGridItem?.dataQuery.data
    }
    return {
      type: 'dataset',
    }
  }

  //  获取当前item relateWidgets 列表
  private get interactList() {
    if (this.currentGridItem?.interactionJson) {
      return this.currentGridItem?.interactionJson.relateWidgets
    }
    return []
  }

  public async created(): Promise<void> {
    // this.initSetting()
  }

  /** 获取当前索引 */
  private getCurrentIndex() {
    return VisualizationStore.gridList.findIndex(
      (item) => VisualizationStore.currentGridItem?.i === item.i
    )
  }

  private onChangeFilterForm(formSetting: KeyValueStore) {
    const index = this.getCurrentIndex()
    if (formSetting.data.title !== undefined) {
      this.updateFilterFormItem(index, formSetting)
      return
    }

    /** 如果关联图表改变了，需要将取消关联的图表复位 */
    if (
      !isEqual(
        this.formData.associationChart,
        formSetting.data.associationChart
      )
    ) {
      VisualizationStore.eventBus.$emit('aschartchange', {
        old: cloneDeep(this.formData.associationChart),
        newValue: formSetting.data.associationChart,
      })
    }
    // 检测到开始节点变化则清空之前的设置
    if (formSetting.data.startNode !== this.formData.startNode) {
      formSetting.data.filterColumns = [{ value: '', type: 'string', step: 1 }]
    }
    // 列信息更新标识, 如果数据变更,则需要更新
    const updateTag = this.formData?.startNode !== formSetting.data.startNode
    // 同步formData信息
    this.formData = {
      ...this.formData,
      ...formSetting.data,
    }

    /** 节点信息变更, 需要同步更新字段信息，关联图表等 */
    if (updateTag) {
      const columnSet = cloneDeep(filterColumnDefault)
      this.checkAndUpdateFilterFormItems(
        {
          data: {
            ...formSetting.data,
            queryData: {},
            filterColumns: columnSet,
          },
        },
        (settingDataSet: any) => {
          this.updateFilterFormItem(index, settingDataSet)
        }
      )
    } else {
      this.updateFilterFormItem(index, formSetting)
    }
  }

  /** 防止触发过快 */
  private updateFilterFormItem = throttle((index: number, formSetting: any) => {
    const chartOptions = VisualizationStore.currentGridItem?.chartOptions || {}
    const chartOptionsSet = {
      ...chartOptions,
      ...formSetting.data,
      associationChart: formSetting.data.associationChart,
    }
    VisualizationStore.updateWidget({
      gridItem: {
        ...VisualizationStore.currentGridItem,
        chartOptions: chartOptionsSet,
      },
      index,
      syncUpdate: true,
      onSuccess: () => {
        VisualizationStore.setCurrentFilterFormAsCharts(
          formSetting.data.associationChart
        )
      },
    })
  }, 1000)

  private onFormSettingChange(formSetting: KeyValueStore) {
    /** 如果回调状态 */
    if (VisualizationStore.isSettingPanelChangeLock) {
      console.error('onFormSettingChange done 拦截成功')
      return
    }
    if (this.chartType === 'filterForm') {
      this.onChangeFilterForm(formSetting)
      return
    }
    if (this.chartType === 'table') {
      this.onChangeTableConfig(formSetting)
      return
    }
    if (GRAPH_ARRAY.includes(this.chartType)) {
      // graph 处理
      // @ts-ignore
      this.parseGraphSettingChange(formSetting)
      return
    }
    const { type, data, widgetInfo } = formSetting
    const isGeo = this.chartType === 'geographicMap'
    if (type === 'property') {
      if (Array.isArray(this.formData.size)) {
        this.formData.size = this.currentGridItem?.chartOptions.size
      }
      // 属性配置变化
      if (!isGeo) {
        this.formData = parseSettingToChartOption({
          ...this.formData,
          ...data,
        })
      } else {
        this.formData = {
          ...this.formData,
          ...data,
        }
      }

      const index = this.getCurrentIndex()
      let newChartOptions: any = this.formData
      if (isGeo) {
        newChartOptions = VisualizationStore.currentGridItem?.chartOptions
        newChartOptions.glyphConfig = {
          ...newChartOptions.glyphConfig,
          ...data,
        }
      }
      if (
        ['barChart', 'lineChart', 'stackBarChart', 'groupBarChart'].includes(
          this.chartType
        )
      ) {
        this.formData.yAxisIsShow = true
        this.formData.xAxisIsShow = true
        this.formData.axisGridIsShow = true
      }
      VisualizationStore.updateWidget({
        gridItem: {
          ...VisualizationStore.currentGridItem,
          chartOptions: newChartOptions,
        },
        index,
      })

      // }
    } else if (type === 'fetch') {
      // 获取数据配置变化
      const { widgetJson, id, type: dataType } = widgetInfo
      const { keys, values } = widgetJson.config
      this.formData = {
        ...this.formData,
        value: data,
        labelKey: keys[0].col,
        valueKey: values[0].col,
        dataId: id,
        dataType,
      }
      VisualizationStore.gridItemBindData({
        query: {
          data: {
            id,
            type: dataType,
            widgetJson,
          },
        },
        data,
        columns: this.fields,
        formData: cloneDeep(this.formData),
      })
    } else if (type === 'interact') {
      const index = this.getCurrentIndex()
      VisualizationStore.updateWidget({
        gridItem: {
          ...VisualizationStore.currentGridItem,
          interactionJson: data,
        },
        index,
      })
    }
  }

  /**
   * graph 配置处理
   */
  private parseGraphSettingChange(formSetting: {
    type: string
    data: { nodes: KeyValueStore[]; edges: KeyValueStore[] } | KeyValueStore
    subData: KeyValueStore[]
  }) {
    const { type, data } = formSetting
    const { dataId, dataType } = this.formData
    const index = this.getCurrentIndex()
    let newGridItem: any = {
      ...VisualizationStore.currentGridItem,
      chartOptions: {
        ...VisualizationStore.currentGridItem?.chartOptions,
        ...this.formData,
        size: VisualizationStore.currentGridItem?.chartOptions.size,
      },
    }

    if (type === 'fetch') {
      // 获取数据
      VisualizationStore.gridItemBindGraphData({
        data,
        formData: {
          dataId,
          dataType,
        },
        targetGridItem: newGridItem,
      })
    }
    if (type === 'property') {
      this.formData = {
        ...this.formData,
        ...data,
      }
      newGridItem.chartOptions = {
        ...newGridItem.chartOptions,
        ...this.formData,
        size: newGridItem.chartOptions.size,
      }
      VisualizationStore.updateWidget({
        gridItem: newGridItem,
        index,
      })
    } else if (type === 'interact') {
      newGridItem = {
        ...VisualizationStore.currentGridItem,
        interactionJson: data,
      }
      VisualizationStore.updateWidget({
        gridItem: newGridItem,
        index,
      })
    }
    VisualizationStore.setCurrentGridItem(newGridItem)
  }

  /**
   * 重置参数
   */
  private onFormSettingReset({ type, widgetInfo }: KeyValueStore) {
    if (type === 'fetch') {
      this.formData = {
        ...this.formData,
        ...widgetInfo,
        labelKey: '',
        valueKey: '',
        groups: undefined,
        // labelIsShow: false,
      }
      if (this.currentGridItem) {
        // @ts-ignore
        this.$set(this.currentGridItem.dataQuery, 'data', {
          ...this.currentGridItem?.dataQuery?.data,
          ...widgetInfo,
          widgetJson: {},
        })
        this.$set(this.currentGridItem.chartOptions, 'value', [])
      }
    }
  }

  @Watch('currentGridItem', { immediate: true, deep: true })
  getCurrentGridItemId(
    newValue: GridItemDataInterface,
    oldValue: GridItemDataInterface
  ): void {
    this.checkStatus(newValue)
    if (
      (newValue && !oldValue) ||
      (newValue &&
        oldValue &&
        (newValue.i !== oldValue.i ||
          newValue.chartType[1] !== oldValue.chartType[1]))
    ) {
      this.formData = {}
      setTimeout(() => {
        this.loadingCount += 1
        this.initSetting()
        this.checkStatus(newValue)
      }, 10)
    } else if (
      newValue &&
      oldValue &&
      !isEqual(newValue.chartOptions, oldValue.chartOptions)
    ) {
      this.initFormData()
    }
  }

  checkStatus(newValue: GridItemDataInterface) {
    if (
      this.currentGridItem &&
      isArray(this.currentGridItem.chartType) &&
      this.currentGridItem.chartType[1] === GEOMAP_NAME
    ) {
      this.setChartOptionStatus(!!(newValue && newValue.chartOptions.value))
      return
    }
    if (
      newValue &&
      newValue.chartOptions.value &&
      newValue.chartOptions.value.length > 0
    ) {
      this.setChartOptionStatus(true)
    } else {
      this.setChartOptionStatus(false)
    }
  }
  public get projectId() {
    return (this.$route.params as any).id
  }

  async initSetting() {
    if (this.currentGridItem) {
      this.formItems = await this.getFormItems()
      this.initFormData()
      this.loadingCount -= 1
    }
  }

  /** 获取表单配置选项 */
  getFormItems = async () => {
    const formItems = ChartProtoConfig[this.chartType] || []
    if (this.chartType === 'filterForm') {
      /** 深度拷贝，防止连带污染 */
      const filterFormItems = await this.getFilterFormConfig(
        cloneDeep(formItems)
      )
      return filterFormItems
    }
    return cloneDeep(formItems)
  }

  setChartOptionStatus(enabled: boolean) {
    this.formItems.forEach((item) => {
      if (item.type !== 'label' && !dataBindKeys.includes(item.name)) {
        item.props = item.props || {}
        this.$set(item.props, 'disabled', !enabled)
      } else if (item.type === 'label' && item.labelbutton) {
        item.props[0].props = item.props[0].props || {}
        this.$set(item.props[0].props, 'disabled', !enabled)
      }
      // geoMap组件暂不支持glyph切换
      if (item.name === 'glyph') {
        this.$set(item.props, 'disabled', true)
      }
    })
  }
  /**
   * 初始化数据
   */
  initFormData() {
    if (
      VisualizationStore.currentGridItem &&
      VisualizationStore.currentGridItem.chartOptions
    ) {
      // const formData: KeyValueStore =
      //   (VisualizationStore.currentGridItem.chartOptions as KeyValueStore) || {}
      // if ( // 查询数据，不确定是否有用，先临时注释，
      //   formData.dataId &&
      //   !gridItemIsMyComponent(VisualizationStore.currentGridItem) &&
      //   !gridItemIsRecommend(VisualizationStore.currentGridItem) &&
      //   !gridItemIsDataClean(VisualizationStore.currentGridItem)
      // ) {
      //   setTimeout(() => {
      //     this.queryDataInfo()
      //   }, 10)
      // }
      // Object.keys(VisualizationStore.currentGridItem.formData).forEach(
      //   (key) => {
      //     this.$set(this.formData, key, formData[key])
      //   }
      // )
      this.formData = {
        ...this.currentGridItem?.chartOptions,
      }

      if (this.chartType === 'filterForm') {
        this.checkAndUpdateFilterFormItems(
          { data: this.formData },
          (settingData: any) => {
            // 关联图表有变化就更新
            if (
              !isEqual(
                settingData.data.associationChart,
                this.currentGridItem?.chartOptions.associationChart
              )
            ) {
              this.updateFilterFormItem(this.getCurrentIndex(), settingData)
            }
          }
        )
      }
      // 设置一遍图例状态
      // this.checkLegendIsDisabled() // 先注释
    }
  }
  // setDataOption(): void {
  //   const options: Array<any> = []
  //   this.projectDataset.forEach((dataItem: any) => {
  //     options.push({
  //       ...dataItem,
  //       text: dataItem.name,
  //       value: dataItem.id,
  //     })
  //   })

  //   this.setOptionByName('dataId', options)
  // }

  /**
   * 设置option
   */
  setOptionByName(name: string, options: Array<any>) {
    this.formItems.forEach((item, index) => {
      if (item.name === 'dataId') {
        this.$set(this.formItems[index].props, 'options', options)
      }
    })
  }

  getDefaultValueByKey(): KeyValueStore {
    if (this.currentGridItem) {
      const formData = getDefaultFormData(this.currentGridItem.chartType)
      return formData
    }
    return {}
  }
  get usedVlaueKeys(): Array<string> {
    let result: Array<string> = []
    if (isArray(this.formData.valueKey)) {
      result = this.formData.valueKey.reduce((rec, item) => {
        const recNew: Array<string> =
          item.value !== '' ? [...rec, item.value] : rec
        return recNew
      }, [])
    } else if (this.formData.valueKey) {
      result = [this.formData.valueKey]
    }

    return result
  }
  onChangeTableConfig(formSetting: any) {
    const { data, widgetInfo, extraFormData = {} } = formSetting
    const { id, type: dataType } = widgetInfo
    this.formData = {
      ...this.formData,
      dataId: id,
      dataType,
      ...extraFormData,
    }
    if (data) {
      this.formData.value = data
    }
    if (this.currentGridItem) {
      const index = this.getCurrentIndex()
      //  for save table title in widgetSave
      VisualizationStore.updateWidget({
        gridItem: {
          ...this.currentGridItem,
          chartOptions: {
            ...this.currentGridItem.chartOptions,
            ...this.formData,
          },
        },
        index,
      })
    }

    // this.$nextTick(() => {
    //   if (this.currentGridItem) {
    //     this.$set(this.currentGridItem.chartOptions, 'columns', ['petal_length'])
    //   }
    // })

    // this.$nextTick(() => {
    //   if (this.currentGridItem) {
    //     this.currentGridItem.formData = this.currentGridItem.formData || {}
    //     this.$set(this.currentGridItem.formData, key, this.formData[key])
    //     if (key === 'title') {
    //       this.$set(this.currentGridItem.formData, 'title', this.formData.title)
    //       this.$set(
    //         this.currentGridItem.chartOptions,
    //         'title',
    //         this.formData.title
    //       )
    //     } else if (key === 'dataId') {
    //       const optionCurrent = item.props.options.find(
    //         (option: KV) => option.value === this.formData[key]
    //       )
    //       if (optionCurrent) {
    //         this.$set(
    //           this.currentGridItem.formData,
    //           'table',
    //           optionCurrent.tableName
    //         )
    //         this.$set(
    //           this.currentGridItem.formData,
    //           'tableNameReal',
    //           optionCurrent.tableName
    //         )
    //       }
    //       this.$set(this.formData, 'column', [])
    //       this.$set(this.currentGridItem.formData, 'column', [])
    //       this.queryDataInfo(true, () => {
    //         this.getWidgetData(this.formData, 'column')
    //       })
    //     } else if (key === 'column') {
    //       this.getWidgetData(this.formData, 'column')
    //     }
    //   }
    // })
  }
  onChangeCheck(callback?: Function): boolean {
    let result: boolean = true
    const gridItem: GridItemDataInterface | gridItemFilterInterface | null =
      VisualizationStore.currentGridItem
    if (gridItem) {
      VisualizationStore.gridList
        .filter((item) => item.chartType === filterTypeName)
        .forEach((item) => {
          if (
            item.fieldConfig &&
            isArray(item.fieldConfig) &&
            item.fieldConfig.length > 0
          ) {
            ;(item.fieldConfig as Array<any>).forEach((fieldInfo) => {
              if (isArray(fieldInfo.associationChart)) {
                ;(fieldInfo.associationChart as Array<any>).forEach(
                  (chartName) => {
                    if (chartName === gridItem.i) {
                      result = false
                    }
                  }
                )
              }
            })
          }
        })
      if (callback) {
        callback(result)
      }
    } else {
      if (callback) {
        callback(false)
      }
      result = false
    }

    return result
  }
  // 由于配置项收起，展开与glyph切换控制选项显示与隐藏，所以这里需要通过事件回调重新恢复配置
  toggleGroup(data: { item: any; isUp: boolean }) {
    if (!data.isUp && this.checkIsGeoMap()) {
      this.onGeoMapGlyphChanged(this.formData.glyph)
    }
  }

  private updateLabelSortY() {
    this.$set(this.formData, 'labelSort', '')
    if (isArray(this.formData.valueKey) && this.formData.valueKey.length > 0) {
      this.formData.valueKey.forEach((valueItem, m) => {
        this.$set(this.formData.valueKey[m], 'sort', '')
      })
    }
  }

  private updateLabelSort() {
    this.$set(this.formData, 'labelSortY', '')
    if (isArray(this.formData.valueKey) && this.formData.valueKey.length > 0) {
      this.formData.valueKey.forEach((valueItem, m) => {
        this.$set(this.formData.valueKey[m], 'sort', '')
      })
    }
  }

  private updateDataId(value: any, item: KeyValueStore) {
    const formDataDefault: KeyValueStore = this.getDefaultValueByKey()
    this.$set(this.formData, 'labelKey', formDataDefault.labelKey || '')
    this.$set(this.formData, 'valueKey', formDataDefault.valueKey || '')
    this.$set(this.formData, 'groupBy', formDataDefault.groupBy || '')
    this.$set(this.formData, 'tableName', item.name)
    // 这里控件那边会用到
    const optionCurrent = item.props.options.find(
      (option: KV) => option.value === value
    )
    if (optionCurrent) {
      this.$set(this.formData, 'tableNameReal', optionCurrent.tableName)
    }
    this.$set(this.formData, 'topK', 20)
    setTimeout(() => {
      this.queryDataInfo(true)
    }, 10)
  }

  private updateLabelKey(value: any) {
    const formDataDefault: KeyValueStore = this.getDefaultValueByKey()
    if (
      value &&
      [
        ...this.usedVlaueKeys,
        this.formData.labelKeyY,
        this.formData.groupBy,
      ].includes(value)
    ) {
      this.$message.error('维度、度量、分组字段必须互斥')
      this.$set(this.formData, 'labelKey', formDataDefault.labelKey || '')
      const index = this.formItems.findIndex(
        (formItem) => formItem.name === 'labelKeyFormat'
      )
      if (index >= 0) {
        this.formItems[index].isHide = true
        this.formData.labelKeyFormat = ''
      }
    } else {
      const index = this.formItems.findIndex(
        (formItem) => formItem.name === 'labelKeyFormat'
      )
      const field = this.fields.find(
        (formItem) => formItem.value === this.formData.labelKey
      )
      if (index >= 0 && field && field.isDate) {
        this.formItems[index].isHide = false
      } else if (index >= 0) {
        this.formItems[index].isHide = true
        this.formData.labelKeyFormat = ''
      }
    }
  }

  private updateLabelKeyY(value: any) {
    const formDataDefault: KeyValueStore = this.getDefaultValueByKey()
    if (
      value &&
      [
        ...this.usedVlaueKeys,
        this.formData.labelKey,
        this.formData.groupBy,
      ].includes(value)
    ) {
      this.$set(this.formData, 'labelKeyY', formDataDefault.labelKeyY || '')
      this.$message.error('维度、度量、分组字段必须互斥')
    }
  }

  private updateValueKey(value: any) {
    const formDataDefault: KeyValueStore = this.getDefaultValueByKey()
    this.usedVlaueKeys.forEach((usedKey, index) => {
      if (
        value &&
        [this.formData.labelKey, this.formData.groupBy].includes(
          this.usedVlaueKeys[index]
        )
      ) {
        this.$message.error('维度、度量、分组字段必须互斥')
        if (isString(this.formData.valueKey)) {
          this.$set(this.formData, 'valueKey', formDataDefault.valueKey || '')
        } else {
          this.$set(this.formData.valueKey[index], 'value', '')
        }
      }
    })

    /**
     * sort 互斥
     */
    if (isArray(this.formData.valueKey) && this.formData.valueKey.length > 0) {
      const find = this.formData.valueKey.find((valueKeyItem) => {
        return valueKeyItem.sort !== '' ? 1 : -1
      })
      if (find) {
        this.$set(this.formData, 'labelSortY', '')
        this.$set(this.formData, 'labelSort', '')
      }
    }
    this.checkLegendIsDisabled()
  }

  private updateGroupBy(value: any) {
    const formDataDefault: KeyValueStore = this.getDefaultValueByKey()
    if (
      value &&
      [this.formData.valueKey, this.formData.labelKey].includes(value)
    ) {
      this.$message.error('维度、度量、分组字段必须互斥')
      this.$set(this.formData, 'groupBy', formDataDefault.groupBy || '')
    }
  }

  private updateNormalChart(chart: any, key: string, value: any) {
    const storeCurrentGridItem: any = VisualizationStore.currentGridItem
    const chartType = Array.isArray(this.currentGridItem?.chartType)
      ? this.currentGridItem?.chartType[1]
      : this.currentGridItem?.chartType
    chart.$set(key, value)
    if (key === 'axisGridIsShow') {
      chart.$set('xAxisGridIsShow', !!value)
      chart.$set('yAxisGridIsShow', !!value)
    }
    if (key === 'axisScaleType') {
      this.formData.xAxisScaleType = value
      this.formData.yAxisScaleType = value
      chart.$set('xAxisScaleType', value)
      chart.$set('yAxisScaleType', value)
    }
    if (key === 'colors') {
      if (
        chartType &&
        ['heatmapMatrix', 'barChart'].includes(chartType) &&
        Array.isArray(this.formData.colors) &&
        (this.formData.colors as Array<string>)[0]
      ) {
        const color = (this.formData.colors as Array<string>)[0]
        this.formData.legendBasicColor = color
        chart.$props.legendBasicColor = color
        chart.$set('legendBasicColor', color)
        this.$set(this.formData, 'legendBasicColor', value[0])
        this.$set(storeCurrentGridItem.formData, 'legendBasicColor', value[0])
        this.$set(
          storeCurrentGridItem.chartOptions,
          'legendBasicColor',
          value[0]
        )
      }
    }
    if (
      key === 'title' &&
      isString(value) &&
      value.length > 0 &&
      this.formData.titleIsShow
    ) {
      chart.$set('titleIsShow', true)
    }

    if (storeCurrentGridItem.formData) {
      storeCurrentGridItem.formData[key] = value
      if (key !== 'valueKey') {
        storeCurrentGridItem.chartOptions[key] = value
      }
      const index = this.getCurrentIndex()
      VisualizationStore.updateWidget({
        gridItem: VisualizationStore.currentGridItem,
        index,
      })
    }
  }

  private updateChart(value: any, key: string) {
    const storeCurrentGridItem: any = VisualizationStore.currentGridItem
    const chart = VisualizationStore.chartInstanceMaps[storeCurrentGridItem.i]
    if (!chart) {
      return
    }

    if (chart.isVueChart && chart.isGeoMap && this.currentGridItem) {
      // geoMap结构特殊,直接更新
      this.$set(this.currentGridItem.chartOptions, key, this.formData[key])
      this.$set(this.currentGridItem.formData, key, this.formData[key])
      if (['dragEnable', 'zoomEnable'].includes(key)) {
        this.$set(this.currentGridItem.chartOptions, 'status', {
          dragEnable: this.formData.dragEnable,
          zoomEnable: this.formData.zoomEnable,
        })
      }
      // this.onSettingChange(key)
    } else {
      this.updateNormalChart(chart, key, value)
    }
  }

  private updateValue(eventOrData: any, key: string, item: KeyValueStore) {
    if (
      key === 'topK' &&
      (!isNumber(this.formData.topK) || this.formData.topK < 1)
    ) {
      this.formData.topK = 1
    }
    const value = [
      'yAxisTickIsShow',
      'xAxisTickIsShow',
      'yAxisGridIsShow',
      'xAxisGridIsShow',
      'axisLayout',
    ].includes(key)
      ? eventOrData
      : this.formData[key]
    /* eslint-disable */
    if (dataWatchKeys.has(key)) {
      if (
        this.currentGridItem &&
        this.currentGridItem.chartOptions &&
        !this.checkIsGeoMap() &&
        gridItemIsMyComponent(this.currentGridItem)
      ) {
        return
      }

      switch (key) {
        case 'showNumber':
          this.formData.showNumber = parseInt(`${this.formData.showNumber}`)
          break
        case 'dataId':
          this.updateDataId(value, item)
          break
        case 'labelSortY':
          this.updateLabelSortY()
          break
        case 'labelSort':
          this.updateLabelSort()
          break
        case 'labelKey':
          this.updateLabelKey(value)
          break
        case 'labelKeyY':
          this.updateLabelKeyY(value)
          break
        case 'valueKey':
          this.updateValueKey(value)
          break
        case 'groupBy':
          this.updateGroupBy(value)
          break
        // case 'glyph':
        //   {
        //     this.onGeoMapGlyphChanged(value)
        //   }
        //   break
        default:
          break
      }
      if (VisualizationStore.currentGridItem) {
        VisualizationStore.currentGridItem.formData[key] = value
      }
      if (key !== 'dataId') {
        setTimeout(() => {
          this.onSettingChange(key)
        }, 100)
      }
    } else if (
      VisualizationStore.currentGridItem &&
      VisualizationStore.currentGridItem.chartOptions
    ) {
      this.updateChart(value, key)
    }
  }

  onChange(eventOrData: any, key: string, item: KeyValueStore) {
    if (
      key === 'dataId' &&
      VisualizationStore.currentGridItem &&
      VisualizationStore.currentGridItem.widgetId
    ) {
      const result = this.onChangeCheck((tag: boolean) => {
        if (!tag && VisualizationStore.currentGridItem) {
          this.formData.dataId =
            VisualizationStore.currentGridItem.formData.dataId
          this.$message.error('组件已关联控件')
        }
      })
      if (!result) {
        return
      }
    }
    if (this.currentGridItem && this.currentGridItem.chartType === 'table') {
      this.onChangeTableConfig(eventOrData)
      return
    }
    setTimeout(() => {
      this.updateValue(eventOrData, key, item)
    }, 10)
  }

  /** 检测legend展示状态 */
  public checkLegendIsDisabled() {
    if (this.currentGridItem) {
      let chartTypeUsed: any = this.currentGridItem.chartType

      if (isArray(this.currentGridItem.chartType)) {
        ;[, chartTypeUsed] = this.currentGridItem.chartType
      } else if (/\|/.test(this.currentGridItem.chartType)) {
        ;[, chartTypeUsed] = this.currentGridItem.chartType.split('|')
      }

      const chartCheck = [
        'groupBarChart',
        'stackBarChart',
        'lineChart',
        'areaChart',
      ]
      if (chartCheck.includes(chartTypeUsed)) {
        const index = this.formItems.findIndex((item) => {
          return item.label === '图例'
        })
        if (
          isArray(this.formData.valueKey) &&
          this.formData.valueKey.length > 1
        ) {
          this.formItems[index].isHide = false
          this.formItems[index].isDisableSub = false
        } else {
          this.formItems[index].isHide = false
          this.formItems[index].isDisableSub = true
          this.formData.legendIsShow = false
        }
      }
    }
  }

  // public doRecommend(): void {
  //   if (this.currentGridItem && gridItemIsRecommend(this.currentGridItem)) {
  //     return
  //   }
  //   if (this.currentGridItem) {
  //     const fields_: Array<any> = this.fields.reduce((rec, column) => {
  //       rec.push({
  //         id: column.value,
  //         type: column.isNumber ? 'quantitative' : 'categorical',
  //       })
  //       return rec
  //     }, [])

  //     const keys = Array.isArray(this.formData.labelKey)
  //       ? this.formData.labelKey
  //       : this.formData.labelKey
  //       ? [this.formData.labelKey]
  //       : []
  //     const values = isArray(this.formData.valueKey)
  //       ? this.formData.valueKey.reduce((rec, item) => {
  //           const rec_: Array<string> =
  //             item.value !== '' ? [...rec, item.value] : rec
  //           return rec_
  //         }, [])
  //       : this.formData.valueKey
  //       ? [this.formData.valueKey]
  //       : []
  //     const specKeys: Array<any> = []
  //     const specValues: Array<any> = []
  //     this.fields.forEach((item) => {
  //       if (keys.includes(item.value)) {
  //         specKeys.push({
  //           id: item.value,
  //           type: item.isNumber ? 'quantitative' : 'categorical',
  //         })
  //       }
  //       if (values.includes(item.value)) {
  //         specValues.push({
  //           id: item.value,
  //           type: item.isNumber ? 'quantitative' : 'categorical',
  //         })
  //       }
  //     })

  //     const table = this.projectDataset.find(
  //       (item) => `${item.id}` === `${this.formData.dataId}`
  //     )
  //     const spec = {
  //       tableName: table ? table.name : '',
  //       dataset: {
  //         id: this.currentGridItem.formData.dataId,
  //         fields: fields_,
  //       },
  //       chartType: (Array.isArray(this.currentGridItem.chartType)
  //         ? this.currentGridItem.chartType[1]
  //         : this.currentGridItem.chartType) as ChartDetailsEnum,
  //       chartConfig: {
  //         groups: [],
  //         keys: specKeys,
  //         values: specValues,
  //       },
  //     }
  //     if (spec) {
  //       setTimeout(() => {
  //         VisualizationStore.recommendVisualization(spec)
  //       }, 100)
  //     }
  //   }
  // }
  checkIsGeoMap() {
    return (
      this.currentGridItem &&
      this.currentGridItem.chartType.includes(GEOMAP_NAME)
    )
  }
  // 根据glyph动态改变formItems设置
  onGeoMapGlyphChanged(glyph: string) {
    GeoMapGlyphChangedCallback(glyph, this.formItems)
  }
  onSettingChange(key: string) {
    if (
      [
        `${GeoMapEnableGlyphTypes.line}`,
        `${GeoMapEnableGlyphTypes.polygon}`,
      ].includes(this.formData.glyph) ||
      (this.formData.dataId &&
        this.formData.labelKey &&
        (this.checkIsGeoMap() ||
          this.usedVlaueKeys.length > 0)) /* && this.formData.aggregateType */
    ) {
      this.getWidgetData(this.formData, key)
    }
  }
  /**
   * 获取筛选参数
   */
  getFilterFormData(dataId: string, componentId: string): KeyValueStore | null {
    const gridFilters = VisualizationStore.gridList.filter((gridItem) => {
      return gridItem.chartType === 'filter' && gridItem.dataId === dataId
    })
    if (gridFilters.length > 0) {
      const result: KeyValueStore = {}
      gridFilters.forEach((item) => {
        item.fieldConfig.forEach((fieldInfo: ControlConfigurationInterface) => {
          if (fieldInfo.associationChart.includes(componentId)) {
            result[fieldInfo.column.value] = {
              compType: fieldInfo.controlRender,
              columnType: fieldInfo.columnType,
              value: fieldInfo.value,
            }
          }
        })
      })
      return result
    } else {
      return null
    }
  }

  getFilterItem(
    fieldName: string,
    value: any,
    controlType: string,
    columnType?: string
  ): KeyValueStore | null {
    let result: any = null
    switch (controlType) {
      case componentTypeEnum.radio:
      case componentTypeEnum.select:
        if (isString(value) && value !== '') {
          result = {
            col: fieldName,
            filterType: '=',
            values: [],
            checkedList: [value],
          }
        }
        break

      case componentTypeEnum.checkbox:
        if (value && isArray(value) && value.length > 0) {
          result = {
            col: fieldName,
            type: columnType,
            filterType: 'in',
            values: [],
            checkedList: value,
          }
        }
        break

      case componentTypeEnum.rangeDay:
        if (
          value &&
          isArray(value) &&
          value.length === 2 &&
          value[0] &&
          value[1]
        ) {
          result = {
            col: fieldName,
            filterType: '[a,b]',
            type: 'timestamp', // timestamp | datetime
            values: [value[0], value[1]],
            format: 'yyyy-MM-dd',
            checkedList: [value[0], value[1]],
          }
        }
        break
      case componentTypeEnum.rangeMonth:
        if (
          value &&
          isArray(value) &&
          value.length === 2 &&
          value[0] &&
          value[1]
        ) {
          result = {
            col: fieldName,
            filterType: '[a,b]',
            type: 'timestamp', // timestamp | datetime
            values: [value[0], value[1]],
            format: 'yyyy-MM',
            checkedList: [value[0], value[1]],
          }
        }

        break
      case componentTypeEnum.rangeYear:
        if (
          value &&
          isArray(value) &&
          value.length === 2 &&
          value[0] &&
          value[1]
        ) {
          result = {
            col: fieldName,
            filterType: '[a,b]',
            type: 'timestamp', // timestamp | datetime
            values: [value[0], value[1]],
            format: 'yyyy',
            checkedList: [value[0], value[1]],
          }
        }
        break
      default:
        break
    }

    return result
  }

  getTableData(filterSend: Array<any>) {
    if (
      this.currentGridItem &&
      this.currentGridItem.formData &&
      this.currentGridItem.chartType === 'table'
    ) {
      const dataSend: KeyValueStore = {
        data: {
          datasetId: this.currentGridItem.formData.dataId,
          projectId: this.projectId,
          // column: this.currentGridItem.formData.column,
          curPage: this.currentGridItem.formData.curPage,
          pageSize: this.currentGridItem.formData.pageSize,
          // filter: filterSend,
          // table: this.currentGridItem.formData.table,
          // mode: 50,
        },
      }
      this.loadingCount += 1
      infoData(dataSend)
        .then((response: any) => {
          this.loadingCount -= 1
          if (response.data.code === 100) {
            if (this.currentGridItem) {
              this.$set(
                this.currentGridItem.formData,
                'curPage',
                response.data.result.page.curPage || 0
              )
              this.$set(
                this.currentGridItem.formData,
                'total',
                response.data.result.page.totalElements || 0
              )
              this.$set(
                this.currentGridItem.formData,
                'pageSize',
                response.data.result.page.pageSize || 1
              )
              this.$set(
                this.currentGridItem.chartOptions,
                'value',
                response.data.result.data || []
              )
              VisualizationStore.visualizationInstance.onSave()
            }
          }
        })
        .catch(() => {
          this.loadingCount -= 1
        })
    } else {
      console.error('call error: getTableData must be used by table')
    }
  }
  getWidgetData(dataSetting: KeyValueStore, key: string = '') {
    if (this.currentGridItem) {
      const filters: KeyValueStore | null = this.getFilterFormData(
        dataSetting.dataId,
        this.currentGridItem.i as string
      )
      const filterSend = [] as Array<any>
      if (filters) {
        Object.keys(filters).forEach((fieldName: string) => {
          const controlRender = filters[fieldName].compType
          const value = filters[fieldName].value
          if (
            (value &&
              !['rangeDay', 'rangeYear', 'rengeMonth'].includes(
                controlRender
              ) &&
              value[0] !== '') ||
            (value &&
              ['rangeDay', 'rangeYear', 'rengeMonth'].includes(controlRender) &&
              value[0] &&
              value[1])
          ) {
            const filterItem = this.getFilterItem(
              fieldName,
              value,
              controlRender,
              filters[fieldName].columnType
            )
            if (filterItem) {
              filterSend.push(filterItem)
            }
          }
        })
      }
      if (this.currentGridItem.chartType === 'table') {
        this.getTableData(filterSend)
        return
      }
      this.loadingCount += 1
      let type = 'dataset'
      if (
        ['dataset', 'task', 'recommend', 'tclean'].includes(
          dataSetting.dataType
        )
      ) {
        type = dataSetting.dataType
      } else if (
        gridItemIsRecommend(this.currentGridItem) &&
        this.currentGridItem.formData.dataType_ === 'recommend'
      ) {
        type = 'recommend'
      }

      const query: KeyValueStore = {
        data: {
          id: dataSetting.dataId,
          type,
          widgetJson: getWidgetJson(dataSetting),
        },
      }

      query.data.widgetJson.config.filters = filterSend

      if (VisualizationStore.currentGridItem) {
        VisualizationStore.currentGridItem.widgetJson = query
      }
      this.$set(this.currentGridItem, 'isLoading', true)
      getWidgetData(query)
        .then((response) => {
          if (this.currentGridItem) {
            this.loadingCount -= 1
            this.$set(this.currentGridItem, 'isLoading', false)
            if (response.data.code === 100) {
              if (
                this.currentGridItem &&
                !this.currentGridItem.chartOptions.titleHeight
              ) {
                this.currentGridItem.chartOptions.colors = this.formData.colors
                this.currentGridItem.chartOptions = {
                  ...this.currentGridItem.chartOptions,
                  // ...{
                  //   titleIsShow: true,
                  //   titleHeight: 44,
                  //   titleFontSize: 16,
                  //   titleFontColor: '#373B52',
                  //   xAxisTickIsShow: false,
                  //   yAxisTickIsShow: false,
                  //   xAxisFontSize: 12,
                  //   xAxisFontColor: '#373B52',
                  //   yAxisFontColor: '#373B52',
                  //   xAxisLineColor: '#e9e9e9',
                  //   xAxisGridColor: '#e9e9e9',
                  //   xAxisLineWidth: 1,
                  //   yAxisLineColor: '#e9e9e9',
                  //   yAxisGridColor: '#e9e9e9',
                  //   xAxisTickColor: '#e9e9e9',
                  //   yAxisTickColor: '#e9e9e9',
                  //   xAxisTitleFontSize: 12,
                  //   xAxisTitlePosition: 'center',
                  //   xAxisRenderMode: 'all',
                  //   yAxisTitleFontSize: 12,
                  //   yAxisTitlePosition: 'center',
                  //   yAxisRenderMode: 'all',
                  // },
                }
              }
              VisualizationStore.gridItemBindData({
                query,
                data: response.data.result,
                columns: this.fields,
                formData: cloneDeep(this.formData),
              })
              if (key !== 'isAggr' && this.currentGridItem) {
                // if (
                //   ['labelKey', 'valueKey', 'groupBy', 'labelKeyY'].includes(key)
                // ) {
                //   setTimeout(() => {
                //     this.doRecommend()
                //   }, 300)
                // }
              }
            }
          }
        })
        .catch((error) => {
          console.error('getWidgetData error:', error)
          this.loadingCount -= 1
          if (this.currentGridItem) {
            this.$set(this.currentGridItem, 'isLoading', false)
          }
        })
    }
  }
  public fields: Array<any> = []

  public clumnCache: KV = {}

  queryDataCallback(
    fields: any = [],
    columnBind: any = [],
    tag?: boolean,
    callback?: Function
  ) {
    this.formItems.forEach((dataItem: KeyValueStore, index: number) => {
      if (dataItem.optionsSourse === 'columns') {
        if (dataItem.name === 'column') {
          this.$set(
            this.formItems[index].bind,
            'options',
            fields.filter((column: KeyValueStore) => {
              return dataItem.optionFilter(column)
            })
          )
          this.$set(this.formItems[index], 'isHide', false)
          if (
            this.currentGridItem &&
            this.currentGridItem.formData &&
            isArray(this.currentGridItem.formData.column) &&
            this.currentGridItem.formData.column.length == 0
          ) {
            this.$set(this.formData, 'column', columnBind)
            this.$set(
              this.currentGridItem.formData,
              'column',
              cloneDeep(columnBind)
            )
          }
        } else {
          this.$set(
            this.formItems[index].props,
            'options',
            fields.filter((column: KeyValueStore) => {
              return dataItem.optionFilter(column)
            })
          )
        }
      }
    })
    this.fields = fields

    // if (tag) {
    //   this.doRecommend()
    // }
    if (callback) {
      callback()
    }
  }
  // 获取数据信息
  queryDataInfo(tag?: boolean, callback?: Function): void {
    const data = this.formData
    if (VisualizationStore.tableColumnCache[`dataId${data.dataId}`]) {
      this.queryDataCallback(
        VisualizationStore.tableColumnCache[`dataId${data.dataId}`].fields,
        VisualizationStore.tableColumnCache[`dataId${data.dataId}`].columnBind,
        tag,
        callback
      )
      return
    }
    this.loadingCount += 1
    if (data.dataId) {
      queryDatasetById({
        data: {
          id: data.dataId,
        },
      })
        .then((response: any) => {
          this.loadingCount -= 1
          if (response.data.code === 100) {
            const fields: any = []
            const columnBind: any = []
            if (
              response.data.result.head &&
              Array.isArray(response.data.result.head) &&
              response.data.result.head.length > 0
            ) {
              response.data.result.head.forEach((head: KeyValueStore) => {
                fields.push({
                  tableId: data.dataId,
                  text: head.name,
                  label: head.name,
                  value: head.name,
                  isDate: 'date' === head.type,
                  isNumber: numberTypes.has(head.desc),
                })
                columnBind.push(head.name)
              })
            }
            VisualizationStore.setTableColumnCache({
              dataId: data.dataId,
              fields,
              columnBind,
            })
            this.queryDataCallback(fields, columnBind, tag, callback)
          }
        })
        .catch((error: any) => {
          console.error(error)
          this.loadingCount -= 1
        })
    }
  }

  /** 获取筛选器的配置信息 */
  private async getFilterFormConfig(formItems: any[]) {
    const pipelieNodes = await this.getProjectDataList()
    formItems.forEach((item: any, i: number) => {
      item.children.forEach((sub: any, j: number) => {
        if (sub.name == 'startNode') {
          formItems[i].children[j].props.options = pipelieNodes
        }
      })
    })
    return formItems
  }

  /**
   * 获取项目下面所有的数据集
   */
  public async getProjectDataList() {
    const parameters = {
      data: {
        projectId: this.projectId,
      },
    }
    const graphDataResponse = await loadListFiles()
    let graphDataList: any[] = []
    if (graphDataResponse.data.code == 100) {
      graphDataList = (graphDataResponse.data.result || []).map((d: any) => {
        return {
          label: d,
          isGraphData: true,
          value: d,
        }
      })
    }
    const result = await queryDatalist2(parameters)
    if (result.data.code === 100) {
      const dataSetList = (result.data?.result[0]?.dataset || []).map(
        (item: any) => {
          return {
            ...item,
            label: item.name,
            value: item.id,
          }
        }
      )
      const pipeline = (result.data?.result[0]?.pipeline || []).map(
        (item: any) => {
          return {
            ...item,
            label: item.name,
            value: item.id,
          }
        }
      )

      return [
        { label: '数据集', items: dataSetList },
        { label: 'Pipeline', items: pipeline },
        { label: 'Graph', items: graphDataList },
      ]
    }
    // const result = await pipelineList({ data: parameters });
    // if(result.data.code === 100) {
    //   const pipeLine = (result.data?.result || [])[0] || null
    //   if(pipeLine) {
    //     return await this.getAllNodeList({ pipelineId: pipeLine.id, id: this.projectId })
    //   }
    // }
    return []
  }

  // /** 获取pipeline所有的节点 */
  // public async getAllNodeList(data: any) {
  //   const result = await allNodeList({data})
  //   if(result.data.code === 100) {
  //     return result.data?.result || [];
  //   }
  //   return []
  // }

  /** 查询graph的attrs信息 */
  async queryGraphWidgetColumn(findNode: any, sub: any) {
    // 这里缓存key与其他业务要做区分
    const cacheKey = `main____${findNode.value}_$`
    const options = await visGraphService.getCache(cacheKey)
    if (options) {
      this.$set(sub.props, 'options', options)
      return
    }
    const result: any = await loadGraphData({
      data: {
        fileName: findNode.value,
        projectId: this.projectId,
      },
    })
    if (result?.data?.code === 100) {
      const columns = getGraphDataColumns(
        result.data.result,
        findNode,
        this.projectId
      )
      sub.props = sub.props || {}
      this.$set(sub.props, 'options', columns)
      visGraphService.save({
        id: cacheKey,
        data: columns,
      })
    } else {
      message.error('获取graph数据字段信息失败')
    }
  }

  /** 设置筛选器控件的筛选字段 */
  private updateFilterColumns(findNode: any, sub: any) {
    if (!findNode) {
      return
    }
    if (findNode.isGraphData) {
      this.loadingCount += 1
      this.queryGraphWidgetColumn(findNode, sub)
      this.loadingCount -= 1
      return
    }
    const queryData = {
      data: {
        id: findNode.id,
        curPage: 1,
        pageSize: 1,
        projectId: this.projectId,
        // datasetId: findNode.value,
        taskId: findNode.value,
        type: findNode.type,
      },
    }

    /** 查询 */
    queryWidgetColumn(queryData).then((res) => {
      if (res.data.code === 100) {
        sub.props = sub.props || {}
        this.$set(
          sub.props,
          'options',
          (res.data?.result?.head || []).map((c: any, k: number) => {
            const colType = (c.desc || '').toLocaleLowerCase()
            const isNumber = numberTypes.has(colType)
            return {
              tableName: findNode.tableName,
              dataId: findNode.id,
              nodeType: findNode.type,
              ...c,
              colType,
              isNumber,
              label: c.name,
              value: c.name,
            }
          })
        )
      } else {
        message.error('获取列数据失败')
      }
    })
  }

  /** 遍历数据获取node 或 data 的数据信息 */
  private getStartNodeInfo(pipelineNodes: any, id: string | number) {
    let result = null as any
    pipelineNodes.forEach((group: any) => {
      if (group && group.items?.length > 0) {
        const temp = group.items.find((n: any) => n.value === id)
        if (temp) {
          result = temp
        }
      }
    })
    return result
  }

  /** 更新筛选表单配置 */
  private async checkAndUpdateFilterFormItems(
    settingData: any,
    callback?: Function
  ) {
    /** 所有的数据信息列表 */
    let pipelineNodes: any[] = []
    /** 当前选中的节点或数据 */
    let findNode: any = null
    let asCharts = [] as any[]
    let subAssociationChart: any
    const formItems = cloneDeep(this.formItems)
    formItems.forEach((item: any) => {
      ;(item.children || []).forEach((sub: any) => {
        if (sub.name === 'startNode') {
          pipelineNodes = sub.props.options || []
          settingData.data.startNode &&
            (findNode = this.getStartNodeInfo(
              pipelineNodes,
              settingData.data.startNode
            ))
        } else if (sub.name === 'filterColumns') {
          /** 更新列信息options */
          this.updateFilterColumns(findNode, sub)
        } else if (sub.name === 'associationChart') {
          subAssociationChart = sub
        }
      })
    })
    asCharts = findNode
      ? await this.updateFilterAssociationChart(
          findNode,
          subAssociationChart,
          settingData
        )
      : []
    settingData.data.associationChart = this.formData.associationChart
      ? this.formData.associationChart
      : asCharts
    console.log(
      'this.formData.associationChart',
      this.formData.associationChart
    )
    settingData.data.isGraph = findNode?.isGraphColumn
    settingData.data.nodeInfo = findNode?.findNode
    settingData.data.starNodeType = findNode?.type
    this.formItems = formItems
    callback && findNode && callback(settingData)
  }

  /** 获取关联graph */
  private updateFilterAssociationGraph(
    startNode: any,
    sub: any,
    settingData: any
  ) {
    const result = [] as any[]
    const valueSet = [] as any[]
    VisualizationStore.gridList.forEach((gridItem: GridItemDataInterface) => {
      if (gridItem && gridItem.chartOptions.dataId === startNode.value) {
        result.push({
          showHander: false,
          label: gridItem.chartOptions.title,
          disabled: false,
          value: gridItem.widgetId,
        })
        valueSet.push(gridItem.widgetId)
      }
    })
    this.$set(sub.props, 'options', result)
    // this.$set(settingData.data, 'associationChart', valueSet)
    // this.$set(this.formData, 'associationChart', valueSet)
    // this.$set(sub, 'defaultValue', valueSet)
    // this.$set(sub, 'value', valueSet)
    return valueSet
  }
  /** 更新关联chart信息 */
  private async updateFilterAssociationChart(
    startNode: any,
    sub: any,
    settingData: any
  ): Promise<Array<any>> {
    let result = [] as any[]
    if (startNode) {
      if (startNode.isGraphData) {
        return this.updateFilterAssociationGraph(startNode, sub, settingData)
      }
      const response = await getRelateWidgets({
        data: {
          dashboardId: VisualizationStore.currentDashboard.id,
          isPublished: false,
          projectId: this.projectId,
          dataType: startNode.type,
          dataId: startNode.id,
          isFilterWidget: true,
        },
      })
      if (response.data?.code === 100) {
        let valueSet: Array<string | number> = []
        this.$set(
          sub.props,
          'options',
          (response.data?.result?.relateWidgets || []).map((item: any) => {
            if (item.status === 'filter_connected') {
              valueSet.push(item.widgetId)
            }
            return {
              ...item,
              showHander: item.status !== 'filter_connected',
              label: item.chartName,
              disabled: false,
              value: item.widgetId,
            }
          })
        )

        valueSet = this.formData.associationChart
          ? this.formData.associationChart
          : valueSet

        this.$set(sub, 'defaultValue', valueSet)
        this.$set(sub, 'value', valueSet)
        this.$set(this.formData, 'associationChart', valueSet)
        result = valueSet
      }
    }
    return result
  }
}
</script>

<style lang="less" scope>
.control-setter {
  height: calc(100% - 46px);
  width: 100%;

  .mask {
    background: rgba(0, 0, 0, 0.05);
    height: 100%;
    position: absolute;
    text-align: center;
    width: 100%;
    z-index: 100;

    .spinner {
      left: 50%;
      position: absolute;
      top: 50%;
      transform: translate(-50%, -50%);
    }
  }

  /deep/ .table-columns {
    display: block;
    height: auto;
    padding-top: 8px;

    .ant-form-item-label {
      float: none;
    }

    .ant-form-item-control-wrapper {
      display: block;
      float: none;
      width: 250px;
    }

    .ant-form-item-control {
      height: auto !important;
      padding-left: 10px;
    }
  }

  /deep/ .ant-form-item label {
    color: rgb(34, 36, 50, 0.6);
  }
}
</style>
